<?php

namespace app\admin\controller;

use app\common\common\model\oldModel\store\Store;
use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Loader;

/**
 * 版本管理
 *
 * @icon fa fa-circle-o
 */
class TableQrcode extends Backend
{

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\common\model\table\TableQrcode();
    }

    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {

            $map = array();//查询条件
            $post = (array)json_decode(input('filter'), true);
            //设置过滤where参数
            $this->filterParam = ['sname'];
            //旧平台门店表
            $storeModel = new Store();
            if( isset( $post['sname']) ){

                $storeId = $storeModel->where( ['sname' => array('like' , '%' . $post['sname'] . '%' )  ] )->column('store_id');
                if( $storeId ){
                    $map['sid'] = array( 'in' , $storeId);
                }
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where( $where )
                ->where( $map )
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where( $where )
                ->where( $map )
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $k => $v){
                //判断当前卡是否绑定 且 存在门店
                if( $v->sid  && $v->status == 2){
                    $list[$k]['sname'] = $storeModel->where( 'store_id' , $v->sid)->value('sname');
                } else {
                    $list[$k]['sname'] = '--';
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 生成二维码
     * @author lgp
     * @datetime 2019-05-13
     */
    public function create_qrcode(){

        if (Request::instance()->isPost()){
            $num = input( 'num/d');
            if( !$num ){
                $this->error(__('Parameter %s can not be empty', ''));
            }
            //增加限制 最大1000
            $max_number = config('create_max_qrcode_num');
            if( $num >  $max_number){
                $this->error( '最多一次生成'.$max_number.'张' );
            }
            //实例化二维码类
            Loader::import('phpqrcode.phpqrcode');
            $object = new \QRcode();//实例化二维码类
            //二维码内容
            $level  = 3;
            $size   = 4;
            $pathname = config('qrcode_path') ."/" . date('Y-m-d') ;
            if( !is_dir( $pathname ) ) { //若目录不存在则创建之
                mkdir( $pathname );
            }
            $errorCorrectionLevel = intval($level) ;//容错级别
            $matrixPointSize = intval($size);//生成图片大小

            $data = [];  //编号
            for ($i = 0 ; $i < $num ; $i++ ){
                $qrcode_sn = get_qrcode_sn();  //获取二维码编号
                $data[$i]['qrcode_sn'] = $qrcode_sn;
                $data[$i]['status'] = 1; //状态  //1未绑定 2已绑定
                $url    = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php?s=/api/qrcode/index/code/' .$qrcode_sn; //二维码内容地址
                $ad = $pathname . '/'. $qrcode_sn . ".png";
                $data[$i]['url'] = $url;
                $data[$i]['path'] = "/" . date('Y-m-d') .'/'. $qrcode_sn . ".png";
                $object->png($url, $ad, $errorCorrectionLevel, $matrixPointSize, 2);
            }
            try {
                $this->model->insertAllTablel( $data );
            } catch (Exception $e) {
                $this->error( '二维码生成失败');
            }
            $this->success( '二维码生成成功');
        } else {
            return $this->view->fetch();
        }



    }

    /**
     * 查看二维码
     */
    public function show(){
        $id = input( 'ids' );
        if( !$id ){
            $this->error( '请选择内容');
        }
        $list = $this->model->findOne( $id );
        $this->assign( 'row' , $list );
        return $this->view->fetch();

    }

    /**
     * 下载二维码
     * @author lgp
     * @datetime 2019-05-13
     */
    public  function down_qrcode(){
        $ids = input( 'ids');
        if( !$ids ){
            $this->error( '请选择要下载的内容');
      //      echo "<script>  Toastr.error( '请选择要下载的内容);</script>";die;
        }
        $list = $this->model->where( 'id' , 'in' , $ids)->select();
        //要下载的文件夹路径
        $filePath = config( 'qrcode_path');
        //生成压缩文件名字
        $zipFileName = config('qrcode_download_path');
        $fileName = date( 'YmdHis') . '.zip';
        $zipFileName = $zipFileName  .   $fileName;
        $path = [];
        foreach ($list as $item ){
            //获取文件名
            $path[] = $filePath  .$item['path'];
        }
        //获取文件信息 打包到zip压缩包
        $zipFlag = zip_archive( $zipFileName , $path);
        if( !$zipFlag ){

            $this->error('打包失败' );
        }
        if(!file_exists($zipFileName)) {
//            echo "<script>  Toastr.error( '文件压缩失败！或者未生成压缩包！！);</script>";die;
            $this->error('文件压缩失败！或者未生成压缩包！！' );
        }

        return json( ['code' => 1 , 'info' => '打包成功' , 'data' =>  $fileName  ]);


    }



    public function downzip (){

        $zipFileName = input( 'zipFile');

        $qrcode_download_path = config('qrcode_download_path');

        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header('Content-disposition: attachment; filename='.basename($qrcode_download_path  . '小程序桌码下载_'.$zipFileName)); //文件名
        header("Content-Type: application/zip"); //zip格式的
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        header('Content-Length: '. filesize($qrcode_download_path.$zipFileName)); //告诉浏览器，文件大小
        @readfile($qrcode_download_path.$zipFileName);
        @unlink($qrcode_download_path.$zipFileName);
    }

}
